﻿using Microsoft.AspNetCore.Mvc;
using IService;
using Model;

namespace WMS.Controllers
{
    public class JurisdictionController : Controller
    {
        private readonly IJurisdictionService _ijs;
        public JurisdictionController(IJurisdictionService jurisdictionService)
        {
            _ijs = jurisdictionService;
        }

        // 主页面
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetAllAsync()
        {
            var jurisdictions = await _ijs.GetAllAsync();
            var result = jurisdictions.Select(j => new
            {
                j.JurID,
                j.JurName,
                j.JurAddress
            }).ToList();
            return Ok(new { code = 200, data = result, msg = "success" });
        }
        /// <summary>
        /// 根据id查询当前菜单模块信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetByIdAsync(int id)
        {
            try
            {
                if (id <= 0) return Json(new { code = 400, msg = "ID无效" });

                var jurisdiction = await _ijs.GetByIdAsync(id);
                if (jurisdiction == null) return Json(new { code = 404, msg = "权限不存在" });

                return Json(new
                {
                    code = 200,
                    data = new
                    {
                        jurisdiction.JurID,
                        jurisdiction.JurName,
                        jurisdiction.JurAddress
                    },
                    msg = "success"
                });
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = $"查询失败：{ex.Message}" });
            }
        }
        /// <summary>
        /// 修改地址
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Name"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update(int id,string Name)
        {
            try
            {
                Jurisdiction date = new Jurisdiction
                {
                    JurID = id,
                    JurAddress= Name
                };
                var result = await _ijs.UpdateAsync(date);
                if (result > 0) 
                {
                    return Json(new { code = 200, msg = "权限修改成功" });
                }

                return Json(new { code = 500, msg = "修改失败，请重试" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = $"服务器错误：{ex.Message}" });
            }
        }
    }
}